package com.sky.service.common.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.aop.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.enumeration.OperationType;
import com.sky.mapper.common.CategoryMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealMapper;


import com.sky.exception.DeletionNotAllowedException;
import com.sky.pojo.Category;
import com.sky.result.PageResult;

import com.sky.service.common.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override

    public int save(CategoryDTO dto) {

        Category category = new Category();
        BeanUtils.copyProperties(dto,category);
        //category.setCreateTime(LocalDateTime.now());
        category.setStatus(1);
        //category.setUpdateTime(LocalDateTime.now());
        //category.setUpdateUser(BaseContext.getCurrentId());
        //category.setCreateUser(BaseContext.getCurrentId());
        int row = categoryMapper.save(category);
        redisTemplate.delete(RedisConstant.CATEGORY_CACHE_PREFIX + dto.getType());
        return row;

    }




    @Override
    public int update(CategoryDTO dto) {
        Category category = new Category();
        BeanUtils.copyProperties(dto,category);
        //category.setUpdateTime(LocalDateTime.now());
        //category.setUpdateUser(BaseContext.getCurrentId());
        int row = categoryMapper.update(category);
        Set<String> keys = redisTemplate.keys(RedisConstant.CATEGORY_CACHE_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
        return row;
    }


    @Override
    public PageResult pageQuery(CategoryPageQueryDTO pagedto) {
        PageHelper.startPage(pagedto.getPage(),pagedto.getPageSize());
        Page<Category> page = categoryMapper.pageQuery(pagedto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public int delete(Long id) {
        Category category = categoryMapper.findById(id);
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Integer count = dishMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        int row = categoryMapper.delete(id);
        redisTemplate.delete(RedisConstant.CATEGORY_CACHE_PREFIX + category.getType());
        return row;
    }

    @Override
    public List<Category> findByType(Integer type) {
        String cacheKey = RedisConstant.CATEGORY_CACHE_PREFIX + type;
        log.info("尝试从Redis读取Key: {}", cacheKey);
        List<Category> list = (List<Category>) redisTemplate.opsForValue().get(cacheKey);
        log.info("Redis返回结果: {}", list);  // 检查是否为 null
        if (list == null || list.isEmpty()) {
            log.info("缓存未命中，从数据库加载并写入缓存");
         list = categoryMapper.findByType(type);
            redisTemplate.opsForValue().set(cacheKey, list);
         } else {
            log.info("缓存命中，直接返回缓存数据");
        }
        return list;
    }

    @Override
    public int StartOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        int row = categoryMapper.update(category);
        Set<String> keys = redisTemplate.keys(RedisConstant.CATEGORY_CACHE_PREFIX + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
        log.info("缓存已清空");
        return row;
    }

    @Override
    public List<Category> list() {
        return categoryMapper.list();
    }


}
